package app

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/config"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

var NacosConfig config.Configer

func InitNacos() {
	if NacosConfig != nil {
		return
	}
	var endpoint = "acm.aliyun.com:8080"
	var accessKey = "LTAIIAEX51n7Y2JV"
	var secretKey = "RtQCxAgx0xR0YUuZaRhf9UdfsgPbo3"
	var namespaceId = "a0325693-b7cd-47f0-a0cd-ccb76e753e96"
	if beego.AppConfig.String("nacos::endpoint") != "" {
		endpoint = beego.AppConfig.String("nacos::endpoint")
	}
	if beego.AppConfig.String("aliyun::accessKey") != "" && beego.AppConfig.String("aliyun::secretKey") != "" {
		accessKey = beego.AppConfig.String("aliyun::accessKey")
		secretKey = beego.AppConfig.String("aliyun::secretKey")
	}
	if beego.AppConfig.String("nacos::namespaceId") != "" {
		namespaceId = beego.AppConfig.String("nacos::namespaceId")
	}
	clientConfig := constant.ClientConfig{
		Endpoint:       endpoint,
		NamespaceId:    namespaceId,
		AccessKey:      accessKey,
		SecretKey:      secretKey,
		TimeoutMs:      5 * 1000,
		ListenInterval: 30 * 1000,
	}
	// Initialize client.
	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"clientConfig": clientConfig,
	})
	if err != nil {
		return
	}
	var dataId = "adx"
	var group = "DEFAULT_GROUP"
	if beego.AppConfig.String("nacos::dataId") != "" {
		dataId = beego.AppConfig.String("nacos::dataId")
	}
	if beego.AppConfig.String("nacos::group") != "" {
		group = beego.AppConfig.String("nacos::group")
	}
	// Get plain content from ACM.
	content, err := configClient.GetConfig(vo.ConfigParam{DataId: dataId, Group: group})
	if err != nil {
		println("nacos error:", err.Error())
	}
	NacosConfig, _ = config.NewConfigData("ini", []byte(content))
	//fmt.Println("content=====", content, "======")

	//定义框架常用参数
	if copyRequestBody, err := NacosConfig.Bool("copyRequestBody"); err != nil {
		beego.BConfig.CopyRequestBody = copyRequestBody
	}
}
